package com.wenwu.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wenwu.common.tag.SysConstants;

/**
 * @project ec-staging
 * @class AuthLoginFilter.java
 * @author zhujiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2014年12月9日 下午4:53:58
 * @description 用户登录认证过滤器
 */
public class AuthLoginFilter implements Filter {

	private List<String> noFilterURL = new ArrayList<String>();

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		boolean isStatic = false;
		// 是否静态化操作
		//System.out.println("路径" + request.getRequestURI());
		String param = request.getParameter("staticparam");
		isStatic = "yes".equals(param);
		String requestURL = request.getRequestURL().toString();
		HttpSession session = request.getSession();
		// 如果支持静态化 、 请求为不需要过滤资源 、或已登录成功 则跳转到目标资源
		if (requestURL.indexOf("mgr")<0||isStatic || isNotFilter(requestURL)
				|| session.getAttribute(SysConstants.LOGIN_KEY) != null) {
			chain.doFilter(request, resp);
			return;
		}
		// 根路径
		HttpServletResponse response = (HttpServletResponse) resp;
		response.addHeader("pragma", "no-cache");
		response.addHeader("cache-control", "no-cache");
		response.addDateHeader("expires", 0);
		// 重定向到登录页面
		String path = request.getContextPath() + "/user/mgr/tologin";
		response.sendRedirect(path);
	}

	/**
	 * 判断是否进行过滤 true 不过滤 false 过滤
	 * 
	 * @return
	 */
	private boolean isNotFilter(String requestURL) {
		for (int i = 0; i < noFilterURL.size(); i++) {
			if (requestURL.indexOf(noFilterURL.get(i)) != -1) {
				return true;
			}
		}
		return false;
	}

	public void init(FilterConfig config) throws ServletException {
		// 获取不需要过滤资源
		String strUrl = config.getInitParameter("noFilterURL");
		if (strUrl != null) {
			String[] method = strUrl.split(",");
			for (int i = 0; i < method.length; i++) {
				noFilterURL.add(method[i]);
			}
		}
	}
}
